<template>
	<view class="page">
		<view class="bg-img">
			<image class="img1" src="/static/img/login/title.png" alt="" />
			<image class="img" src="/static/img/login/bg.png" alt="" />
		</view>
		<view class="form">
			<view v-if="loginType==2" class="padding-lr-34 form-item text-555 s-flex-r-s-c">
				<image class="icon" src="/static/img/login/mobile.png" alt="" />
				<u-input class="form-inp padding-left-18 line-height-76 height-76" v-model="form.account"
					placeholder="请输入账号" clearable placeholderClass="inp-lh" border="none">
				</u-input>
			</view>
			<view v-if="loginType==2" class="padding-lr-34 form-item text-555 s-flex-r-s-c">
				<image class="icon" src="/static/img/login/lock.png" alt="" />
				<u-input class="form-inp padding-left-18 line-height-76 height-76" v-model="form.password"
					placeholder="请输入密码" password clearable placeholderClass="inp-lh" border="none">
				</u-input>
			</view>
			<view v-if="loginType==1" class="padding-lr-34 form-item text-555 s-flex-r-s-c">
				<image class="icon" src="/static/img/login/mobile.png" alt="" />
				<u-input class="form-inp padding-left-18 line-height-76 height-76" v-model="form.mobile"
					placeholder="请输入手机号" clearable placeholderClass="inp-lh" border="none">
				</u-input>
			</view>
			<view v-if="loginType==1" class="padding-lr-34 form-item text-555 s-flex-r-s-c">
				<image class="icon" src="/static/img/login/dun.png" alt="" />
				<u-input class="padding-left-18 line-height-76 height-76" v-model="form.captcha" password clearable
					placeholder="请输入验证码" placeholderClass="inp-lh" border="none"></u-input>
				<view class="send" @click="sendCode">{{getCode}}</view>
			</view>


<!-- 			<view class="toast">
				忘记密码？
			</view> -->
			<view class="btn s-flex-r-c-c" @click="loginBtn">
				<text>登录</text>
			</view>
			<view class="xieyi s-flex-r-c-c" :style="{visibility:checked?'hidden':'visible'}">
				<text>请勾选相关协议</text>
				<view class="jiao">

				</view>
			</view>
			<view class="t-xieyi s-flex-r-s-c">
				<image @click="checked=!checked" v-if="checked" class="icon circle" src="/static/img/login/yes.png"
					alt="" />
				<view @click="checked=!checked" v-else class="circle">

				</view>
				<view class="text">
					<!-- 1用户协议,2隐私协议3商会介绍4会员介绍 -->
					我已阅读并同意<text class="t" @click="go(`/pages/h5-details/h5-details?type=1`)">《用户协议》</text>与<text class="t" @click="go(`/pages/h5-details/h5-details?type=2`)">《隐私协议》</text>
				</view>
			</view>
			<view class="other-login s-flex-r-c-c">
				<view class="item s-flex-c-s-c" @click="wxhandleLogin">
					<image class="icon" src="/static/img/login/wx.png" alt="" />
					<text>微信授权登陆</text>
				</view>
				<view v-if="loginType==2" class="item s-flex-c-s-c" @click="loginType=1">
					<image class="icon" src="/static/img/login/dun2.png" alt="" />
					<text>验证码登录</text>
				</view>
				<view v-if="loginType==1" class="item s-flex-c-s-c" @click="loginType=2">
					<image class="icon" src="/static/img/login/account.png" alt="" />
					<text>账号密码登录</text>
				</view>
			</view>
		</view>
		
		<up-popup :show="show3" @close="close3" @open="open3">
			<view class="wrap">
				<image @click="close3" class="close-img" src="/static/img/login/close.png" alt="" />
				<view class="logo s-flex-r-c-c">
					<image class="img" src="/static/img/login/title.png" alt="" />
				</view>
				<button class="btn s-flex-r-c-c" open-type="getPhoneNumber" @getphonenumber="getUserPhone3">
					同意获取手机号并绑定
				</button>
			</view>
		</up-popup>
	</view>
</template>

<script setup>
	import {
		ref,
		computed,
		getCurrentInstance
	} from 'vue';
	import {
		onLoad
	} from "@dcloudio/uni-app"
	const {proxy} = getCurrentInstance()
	// 创建响应式数据  
	const show3 = ref(false);  
	  
	// 定义方法  
	function open3() {  
	  // 打开逻辑，比如设置 show 为 true  
	  show3.value = true;  
	  // console.log('open');  
	}  
	  
	function close3() {  
	  // 关闭逻辑，设置 show 为 false  
	  show3.value = false;  
	  // console.log('close');  
	}  
	// 1 密码 2手机
	const loginType = ref(1)
	const getCode = ref('发送验证码')
	const userPhone = ref('')
	const access_token = ref('')
	const checked = ref(false)
	const timerFlag = ref(false)
	const wxLoginForm = ref({
		code: "",
		encryptedIv: "",
		encryptedData: "",
	});
	let form = ref({
		account:'',
		password:'',
		mobile: '',
		captcha: '',
	})
	let canSub = computed(() => {
		return form.value.mobile && form.value.captcha;
	});
	function getUserPhone3(e) {
		// 获取到回调信息，需要code(与登录login的code不同)
		console.log("回调返回的信息：", e)
		wxLoginForm.value.iv = e.detail.iv;
		wxLoginForm.value.encryptedData = e.detail.encryptedData;
		proxy.$request({
			url: '/api/user/getuserphonenumber',
			header: "application/x-www-form-urlencoded",
			data:{
				access_token:access_token.value,
				code: e.detail.code
			}
		}).then(res => {
			if (res.code ==0) {
				return proxy.$toast(res.msg)
			} else if(res.code == 1) {
				userPhone.value = res.data.phone_info.phoneNumber;
				show3.value = false; 
				uni.getProvider({
					service: 'oauth',
					success: (res) => {
						if (res.provider.some(i=>i=="weixin")) {
							uni.login({
								provider: "weixin",
								success: (loginRes) => {
									wxLoginForm.value.code = loginRes.code
									sendWxLoginFormToLocalService2()
								},
								fail:(err)=>{
									console.log('err: ', err)
								}
							})
						}
					}
				})
			}
		}).catch(() => {
			console.log('登录失败')
		})
		return false;
		uni.request({
			url: 'https://api.weixin.qq.com/cgi-bin/stable_token',
			method: 'POST',
			data: {
				appid: 'wx241184274eb4da97',
				secret: '1b3222aa555169085f3865408ce52bfd',
				grant_type: 'client_credential'
			},
			success(res) {
				console.log('获取access_token信息：', res)
				// 保存access_token的操作，小编这里样例，就直接放在data中了
				// _this.accessToken = res.data.access_token
				uni.request({
					url: `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${res.data.access_token}`,
					method: 'POST',
					data: {
						code: e.detail.code
						// openid: _this.openid (openid非必填，所以不需要先获取用户信息，再获取手机号)
					},
					success(res) {
						userPhone.value = res.data.phone_info.phoneNumber;
						show3.value = false;  
						uni.getProvider({
							service: 'oauth',
							success: (res) => {
								if (res.provider.some(i=>i=="weixin")) {
									uni.login({
										provider: "weixin",
										success: (loginRes) => {
											wxLoginForm.value.code = loginRes.code
											sendWxLoginFormToLocalService2()
										},
										fail:(err)=>{
											console.log('err: ', err)
										}
									})
								}
							}
						})
					}
				})
			}
		})
	}
	/**微信授权登录**/
	function wxhandleLogin() {
		uni.getProvider({
			service: 'oauth',
			success: (res) => {
				if (res.provider.some(i=>i=="weixin")) {
					uni.login({
						provider: "weixin",
						success: (loginRes) => {
							wxLoginForm.value.code = loginRes.code
							uni.getUserInfo({
								success: (res2) => {
									wxLoginForm.value.iv = res2.iv;
									wxLoginForm.value.encryptedData = res2.encryptedData;
									sendWxLoginFormToLocalService()
								}
							})
						},
						fail:(err)=>{
							console.log('err: ', err)
							
						}
					})
				}
			}
		})
	}

	function sendWxLoginFormToLocalService() {
		uni.showLoading({
			title:"加载中"
		})
		proxy.$request({
			url: '/api/user/thirdCode',
			header: "application/x-www-form-urlencoded",
			data:{
				code:wxLoginForm.value.code,
				platform:"wechat"
			}
		}).then(res => {
			uni.hideLoading()
			if (res.code == 405) {
				show3.value=true;
				access_token.value = res.data.access_token;
			} else if(res.code == 1) {
				// token
				proxy.$toast("登录成功");
				uni.setStorageSync('token', res.data.userinfo.token)
				uni.setStorageSync('userinfo', res.data.userinfo)
				uni.reLaunch({
					url: "/pages/index/index"
				})
			}else{
				return proxy.$toast(res.msg)
			}
		}).catch(() => {
			console.log('登录失败')
		})
	}
	function sendWxLoginFormToLocalService2() {
		proxy.$request({
			url: '/api/user/third',
			header: "application/x-www-form-urlencoded",
			data:{
				code:wxLoginForm.value.code,
				mobile:userPhone.value,
				iv: wxLoginForm.value.iv,
				encryptedData: wxLoginForm.value.encryptedData,
				platform:"wechat"
			}
		}).then(res => {
			if (res.code == 0) {
				return proxy.$toast(res.msg)
			} else {
				proxy.$toast("登录成功");
				uni.setStorageSync('token', res.data.userinfo.token)
				uni.setStorageSync('userinfo', res.data.userinfo)
				uni.reLaunch({
					url: "/pages/index/index"
				})
			}
		}).catch(() => {
			console.log('登录失败')
		})
	}
	let rules = ref({
		'mobile': {
			type: 'string',
			required: true,
			message: '请填写账户',
			trigger: ['blur', 'change']
		},
		'password': {
			type: 'string',
			required: true,
			message: '请输入密码',
			trigger: ['blur', 'change']
		}
	})
	onLoad((e) => {
		console.log('e: ', e)
		if(e.loginType){
			loginType.value=e.loginType
		}
	})

	function loginBtn() {
		// 1 验证码登录 2账户密码
		if(!checked.value){
			return proxy.$toast("请勾选协议继续")
		}
			console.log('loginType.value: ', loginType.value)
		if((loginType.value==1)&&(!form.value.mobile||!form.value.captcha)){
			return proxy.$toast("请输入手机号验证码")
		}
		
		if((loginType.value==2)&&(!form.value.account||!form.value.password)){
			return proxy.$toast("请输入账户密码")
		}
		const url = loginType.value ==1?"api/user/mobilelogin":"/api/user/login";
		proxy.$request({
			url: url,
			header: "application/x-www-form-urlencoded",
			data: form.value
		}).then(res => {
			if (res.code == 0) {
				return proxy.$toast(res.msg)
			} else {
				// token
				proxy.$toast("登录成功");
				uni.setStorageSync('token', res.data.userinfo.token)
				uni.setStorageSync('userinfo', res.data.userinfo)
				uni.reLaunch({
					url: "/pages/my/index"
				})
			}
		})
	}

	function sendCode() {
		if (!/[0-9]{11}/.test(form.value.mobile)) {
			uni.showToast({
				icon: 'none',
				title: '请输入正确的手机号'
			})
			return
		}
		if (timerFlag.value === false) {
			proxy.$request({
				url: 'api/sms/send',
				header: "application/x-www-form-urlencoded",
				data: {
					event: "mobilelogin",
					mobile: form.value.mobile
				}
			}).then(res => {
				if (res.code == 0) {
					return proxy.$toast(res.msg)
				} else {
					timerFlag.value = !timerFlag.value
					uni.showToast({
						icon: 'none',
						title: res.msg
					})
					countDown(60)
				}
			})
		}
	}

	function countDown(time) {
		let count = time
		setTimeout(() => {
			count--
			if (time <= 0) {
				getCode.value = '获取验证码'
				timerFlag.value = false
			} else if (count !== time) {
				getCode.value = '重新获取' + count
				countDown(count)
			}
		}, 1000)
	}

	function register() {
		console.log('注册');
		uni.switchTab({
			url: `/pages/index/index`
		});
	}

	function ask() {
		console.log('问号');
	}

	function searchPassword() {
		console.log('找回密码');
	}
</script>

<style lang="scss" scoped>
	.page {
		background: #FFFFFF;
		min-height: 100vh;
		padding-top: 130rpx;
		padding-bottom: 24rpx;
		box-sizing: border-box;
	}

	.bg-img {
		position: relative;

		.img {
			width: 750rpx;
			height: 374rpx;
		}

		.img1 {
			position: absolute;
			top: 4rpx;
			left: 290rpx;
			width: 169rpx;
			height: 88rpx;
		}
	}

	.form {
		margin-top: 34rpx;
		background: #FFFFFF;

		.form-item {
			width: 686rpx;
			height: 104rpx;
			background: #F8F8F8;
			border-radius: 8rpx 8rpx 8rpx 8rpx;
			box-sizing: border-box;
			margin: 0 32rpx;
			margin-bottom: 40rpx;

			.icon {
				width: 28rpx;
				height: 28rpx;
				margin:0 18rpx 0 34rpx;
			}

			.send {
				font-weight: 400;
				font-size: 28rpx;
				color: #076AFB;
				line-height: 76rpx;
			}
		}

		.toast {
			font-weight: 400;
			font-size: 28rpx;
			color: #076AFB;
			line-height: 76rpx;
			padding: 0 32rpx;
		}

		.btn {
			margin: 0 auto;
			width: 686rpx;
			height: 108rpx;
			background: linear-gradient(128deg, #FF9839 0%, #FF7139 100%);
			border-radius: 60rpx 60rpx 60rpx 60rpx;
			font-weight: 800;
			font-size: 32rpx;
			color: #FFFFFF;
			line-height: 60rpx;
		}

		.xieyi {
			margin-left: 34rpx;
			margin-top: 72rpx;
			width: 204rpx;
			height: 44rpx;
			background: #FFF1EB;
			border-radius: 22rpx 22rpx 22rpx 22rpx;
			font-weight: 400;
			font-size: 24rpx;
			color: #FF7139;
			line-height: 28rpx;
			position: relative;

			.jiao {
				position: absolute;
				bottom: -10rpx;
				left: 16rpx;
				width: 16rpx;
				height: 16rpx;
				background: #FFF1EB;
				border-radius: 0rpx 0rpx 0rpx 0rpx;
				transform: rotate(45deg);
			}
		}

		.t-xieyi {
			margin-left: 34rpx;
			margin-top: 28rpx;

			.circle {
				width: 40rpx;
				height: 40rpx;
				border-radius: 20rpx;
				border: 2rpx solid #999999;
				margin-right: 16rpx;
				box-sizing: border-box;
			}

			.icon {
				border: none;
			}

			.text {
				font-weight: 400;
				font-size: 28rpx;
				color: #666666;
				line-height: 33rpx;
				text-align: left;

				.t {
					color: #FF7139;
				}
			}
		}

		.other-login {
			margin-top: 66rpx;

			.item {
				flex: 1;
			}

			.icon {
				width: 100rpx;
				height: 100rpx;
				margin-bottom: 28rpx;
			}

			font-weight: 400;
			font-size: 28rpx;
			color: #333333;
			line-height: 33rpx;
		}
	}
	.wrap{
		padding-top: 34rpx;
		padding-bottom: 24rpx;
		position: relative;
		.close-img{
			position: absolute;
			right: 32rpx;
			top: 32rpx;
			width: 32rpx;
			height: 32rpx;
		}
		.logo{
				margin: 0 auto;
				width: 148rpx;
				height: 148rpx;
				background: #FFFFFF;
				border-radius: 74rpx;
				border: 2rpx solid #CC5610;
				margin-bottom: 64rpx;
			.img{
				width: 122rpx;
				height: 64rpx;
			}
		}
		.btn{
			margin: 0 auto;
			width: 686rpx;
			height: 108rpx;
			background: linear-gradient( 128deg, #FF9839 0%, #FF7139 100%);
			border-radius: 60rpx 60rpx 60rpx 60rpx;
			font-weight: 800;
			font-size: 32rpx;
			color: #FFFFFF;
			line-height: 60rpx;
		}
		.xieyi{
			margin-left: 34rpx;
			margin-top: 72rpx;
			width: 204rpx;
			height: 44rpx;
			background: #FFF1EB;
			border-radius: 22rpx 22rpx 22rpx 22rpx;
			font-weight: 400;
			font-size: 24rpx;
			color: #FF7139;
			line-height: 28rpx;
			position: relative;
			.jiao{
				position: absolute;
				bottom: -10rpx;
				left: 16rpx;
				width: 16rpx;
				height: 16rpx;
				background: #FFF1EB;
				border-radius: 0rpx 0rpx 0rpx 0rpx;
				transform: rotate(45deg);
			}
		}
		.t-xieyi{
			margin-left: 34rpx;
			margin-top: 28rpx;
			.circle{
				width: 40rpx;
				height: 40rpx;
				border-radius: 20rpx;
				border: 2rpx solid #999999;
				margin-right: 16rpx;
				box-sizing: border-box;
			}
			.icon{
				border: none;
			}
			.text{
				font-weight: 400;
				font-size: 28rpx;
				color: #666666;
				line-height: 33rpx;
				text-align: left;
				.t{
					color: #FF7139;
				}
			}
		}
		.other-login{
			margin-top: 66rpx;
			.item{
				flex: 1;
			}
			.icon{
				width: 100rpx;
				height: 100rpx;
				margin-bottom: 28rpx;
			}
			font-weight: 400;
			font-size: 28rpx;
			color: #333333;
			line-height: 33rpx;
		}
	}
</style>